#!/usr/bin/env python
# -*- coding: utf-8 -*-

import base64
import csv
import json
import random
import re
import time

import matplotlib
import os
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import requests
from matplotlib.gridspec import GridSpec
import matplotlib.patches as mpatches
from jingdong_order_synchronization_kuaipu.dingding_robot.media_upload import MediaUpload
from jingdong_order_synchronization_kuaipu.dingding_robot.messages_push import MessagePush
from jingdong_order_synchronization_kuaipu.get_jingdong_messages.get_jingdong_order import get_jingdong_order_datas


# 设置显示选项以打印所有列
pd.set_option('display.max_columns', None)  # 显示所有列
pd.set_option('display.expand_frame_repr', False)  # 禁止换行
pd.set_option('display.max_colwidth', None)  # 显示完整列内容（不截断）
class SaveJingdongSynchronizationDatas(object):
    def __init__(self, message):
        self.message = message
        order_create_date = self.message['request']['add_jingdong_order']['order_create_date']
        date_obj = datetime.strptime(order_create_date, '%Y-%m-%d %H:%M:%S')
        self.current_year = date_obj.year
        self.current_month = date_obj.month
        self.directory = f'../all_jingdong_order_datas/all_jingdong_order_datas/京东订单-{self.current_year}'
        self.csv_file = f'../all_jingdong_order_datas/all_jingdong_order_datas/京东订单-{self.current_year}/京东订单-{self.current_year}-{self.current_month}.csv'

        # 精简后的headers
        self.headers = {
            "branch_id": "分支机构",
            "jingdong_business_model": "业务模式",
            "jingdong_order_id": "订单号",
            "jingdong_order_status": "订单状态",
            "jingdong_consignee_name": "收货人姓名",
            "jingdong_consignee_address": "收货地址",
            "jingdong_phone": "联系电话",
            "order_create_date": "下单时间",
            "jingdong_ware_name": "商品名称0",
            "jingdong_sku": "商品编码0",
            "jingdong_ware_brand": "品牌0",
            "jingdong_ware_category": "品目0",
            "jingdong_ware_model": "型号0",
            "jingdong_ware_num": "采购数量0",
            "jingdong_jd_price": "京东单价",
            "jingdong_jd_total_price": "京东总价",
            "jingdong_procurement_single_price": "采购单价0",
            "jingdong_procurement_total_price": "采购总价0"
        }

        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

    def _get_key_fields(self):
        return [
            "jingdong_order_id",  # 主键
            "jingdong_sku",  # 商品唯一标识
            "order_create_date"  # 时间维度
        ]

    def _read_existing_data(self):
        if not os.path.exists(self.csv_file):
            return []
        with open(self.csv_file, 'r', newline='', encoding='utf-8-sig') as f:
            return list(csv.DictReader(f))

    def _write_data(self, data):
        with open(self.csv_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.DictWriter(f, fieldnames=self.headers.keys())
            writer.writeheader()
            writer.writerows(data)

    def _process_items(self, items):
        existing_data = self._read_existing_data()
        key_fields = self._get_key_fields()

        # 转换现有数据的key
        existing_keys = set()
        for row in existing_data:
            key_tuple = tuple(str(row[k]).strip() for k in key_fields)
            existing_keys.add(key_tuple)

        # 处理新数据
        new_rows = []
        for item in items:
            # 生成当前条目key
            current_key = tuple(str(item.get(k, '')).strip() for k in key_fields)

            # 检查是否已存在
            if current_key not in existing_keys:
                # 标准化数据格式
                standardized = {k: str(v).strip() if v is not None else ''
                                for k, v in item.items()
                                if k in self.headers}

                # 填充完整结构
                complete_row = {k: standardized.get(k, '') for k in self.headers}
                new_rows.append(complete_row)
                existing_keys.add(current_key)  # 防止同批重复

        if new_rows:
            self._write_data(existing_data + new_rows)

    def save_orders(self):
        """统一保存入口"""
        base_info = self.message['request']['add_jingdong_order']
        order_bodies = self.message['request']['add_jingdong_order_bodys']['add_jingdong_order_body']

        processed = []
        for body in order_bodies:
            # 合并基础信息和商品信息
            merged = {
            **base_info,
            **body,
            # 确保包含所有字段
            **{k: '' for k in self.headers if k not in base_info and k not in body}
            }
            # 数值类型转换
            for price_field in ['jingdong_jd_price', 'jingdong_jd_total_price',
                                'jingdong_procurement_single_price', 'jingdong_procurement_total_price']:
                merged[price_field] = str(float(merged.get(price_field, 0)))

            processed.append(merged)

        self._process_items(processed)
class GetOrderDatas():
    def __init__(self):
        with open("../jingdong_order_synchronization_kuaipu/auth/jingdong_cookies.json", "r") as f:
            cookie_data = json.load(f)
            jsessionid_list = []
            # for cookie in cookie_data:
            #     print(cookie)
            #     if cookie["name"] == "JSESSIONID":
            #         print(cookie["value"])
            JSESSIONID = [cookie["value"] for cookie in cookie_data if cookie["name"] == "JSESSIONID"]
            flash = [cookie["value"] for cookie in cookie_data if cookie["name"] == "flash"]
            self.zi_jingdong_cookie = f"flash={random.choice(flash)};JSESSIONID={random.choice(JSESSIONID)};"
        with open("../jingdong_order_synchronization_kuaipu_zhuzhanghao/auth/jingdong_cookies.json", "r") as f:
            cookie_data = json.load(f)
            jsessionid_list = []
            # for cookie in cookie_data:
            #     print(cookie)
            #     if cookie["name"] == "JSESSIONID":
            #         print(cookie["value"])
            JSESSIONID = [cookie["value"] for cookie in cookie_data if cookie["name"] == "JSESSIONID"]
            flash = [cookie["value"] for cookie in cookie_data if cookie["name"] == "flash"]
            self.zhu_jingdong_cookie = f"flash={random.choice(flash)};JSESSIONID={random.choice(JSESSIONID)};"
        # print(self.zi_jingdong_cookie,self.zhu_jingdong_cookie)
    def get_daily_zi_orders(self,new_start_time_str,new_end_time_str):
        zi_headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "cookie": self.zi_jingdong_cookie,
        }
        zi_payload = {
            "startTime": new_start_time_str,
            "endTime": new_end_time_str,
            "_search": "false",
            "nd": int(round(time.time() * 1000)),
            "rows": 100,
            "page": 1,
            "sidx": "orderId asc, groupString asc,",
            "sord": "asc",
            "orderId": "",
            "sku": "",
            "poId": "",
            "roId": "",
            "shipNo": "",
            "phone": "",
            "orderState": "",
            "businessType": "",
            "pin": "",
            "paymentType": "",
            "vendorStoreId": "",
            "ouId": "",
        }
        url = "https://pdropship.jd.com/queryOrder/queryOrderList"
        response = requests.post(url, headers=zi_headers, data=zi_payload)
        datas_json = response.json()["rows"]
        print(len(datas_json))
        detail_consignee_name_address = "https://pdropship.jd.com/virtualNumber/getConsigneeInfo"
        detail_consignee_phone = "https://pdropship.jd.com/virtualNumber/bindVirtualNumber"
        zi_jingdong_orders_messages = []
        for data in datas_json:
            jingdong_order_status = data["operatorStateName"]
            jingdong_order_id = data["orderId"]
            form_data = {
                "orderId": jingdong_order_id,
            }
            detail_consignee_name_address_response = requests.post(detail_consignee_name_address, headers=zi_headers,
                                                                   data=form_data)
            detail_consignee_name_addres_json = detail_consignee_name_address_response.json()["userdata"][
                "consigneeInfo"]
            jingdong_consignee_name = re.sub(r"\[[^\]]*\]", "",
                                             detail_consignee_name_addres_json["consigneeName"])
            jingdong_consignee_address = re.sub(r"\[[^\]]*\]", "",
                                                detail_consignee_name_addres_json[
                                                    "consigneeAddress"])
            detail_consignee_phone_response = requests.post(detail_consignee_phone, headers=zi_headers,
                                                            data=form_data)
            detail_consignee_phone_json = detail_consignee_phone_response.json()["userdata"]["virtualNumberInfo"]
            jingdong_phone = detail_consignee_phone_json["virtualNumber"]
            order_create_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data["orderCreateDate"] / 1000))

            add_jingdong_order = {
                "branch_id": "金穗隆(广州)信息科技有限公司",
                "jingdong_business_model": "电商销售",
                "jingdong_order_id": jingdong_order_id,
                "jingdong_order_status":jingdong_order_status,
                "jingdong_consignee_name": jingdong_consignee_name,
                "jingdong_consignee_address": jingdong_consignee_address,
                "jingdong_phone": jingdong_phone,
                "order_create_date": order_create_date
            }
            add_jingdong_order_body = []
            for detail_data in data["orderDetailList"]:
                jd_price = detail_data['jdPrice']
                procurement_single_price = detail_data["poPrice"]
                ware_num = detail_data["wareNum"]
                jd_total_price = jd_price * ware_num
                procurement_total_price = procurement_single_price * ware_num
                ware_name = detail_data["wareName"]
                sku = detail_data["sku"]
                add_jingdong_order_dict = {
                    # "jingdong_ware_name": ware_name,
                    "jingdong_sku": sku,
                    "jingdong_ware_brand": "",
                    "jingdong_ware_category": "",
                    "jingdong_ware_model": "",
                    "jingdong_ware_num": ware_num,
                    "jingdong_jd_price": jd_price,
                    "jingdong_jd_total_price": jd_total_price,
                    "jingdong_procurement_single_price": procurement_single_price,
                    "jingdong_procurement_total_price": procurement_total_price,
                }
                add_jingdong_order_body.append(add_jingdong_order_dict)
            requests_dict = {
                "add_jingdong_order": add_jingdong_order,
                "add_jingdong_order_bodys": {
                    "add_jingdong_order_body": add_jingdong_order_body
                }
            }
            zi_jingdong_orders_messages.append(requests_dict)
        print(f"jingdong_orders_messages:{zi_jingdong_orders_messages}")
        return zi_jingdong_orders_messages
    def get_daily_zhu_orders(self,new_start_time_str,new_end_time_str):
        zhu_headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "cookie": self.zhu_jingdong_cookie,
        }
        zhu_payload = {
            "startTime": new_start_time_str,
            "endTime": new_end_time_str,
            "_search": "false",
            "nd": int(round(time.time() * 1000)),
            "rows": 100,
            "page": 1,
            "sidx": "orderId asc, groupString asc,",
            "sord": "asc",
            "orderId": "",
            "sku": "",
            "poId": "",
            "roId": "",
            "shipNo": "",
            "phone": "",
            "orderState": "",
            "businessType": "",
            "pin": "",
            "paymentType": "",
            "vendorStoreId": "",
            "ouId": "",
        }
        url = "https://pdropship.jd.com/queryOrder/queryOrderList"
        response = requests.post(url, headers=zhu_headers, data=zhu_payload)
        datas_json = response.json()["rows"]
        print(len(datas_json))
        detail_consignee_name_address = "https://pdropship.jd.com/virtualNumber/getConsigneeInfo"
        detail_consignee_phone = "https://pdropship.jd.com/virtualNumber/bindVirtualNumber"
        zhu_jingdong_orders_messages = []
        for data in datas_json:
            jingdong_order_status = data["operatorStateName"]
            jingdong_order_id = data["orderId"]
            form_data = {
                "orderId": jingdong_order_id,
            }
            detail_consignee_name_address_response = requests.post(detail_consignee_name_address, headers=zhu_headers,
                                                                   data=form_data)
            detail_consignee_name_addres_json = detail_consignee_name_address_response.json()["userdata"][
                "consigneeInfo"]
            jingdong_consignee_name = re.sub(r"\[[^\]]*\]", "",
                                             detail_consignee_name_addres_json["consigneeName"])
            jingdong_consignee_address = re.sub(r"\[[^\]]*\]", "",
                                                detail_consignee_name_addres_json[
                                                    "consigneeAddress"])
            detail_consignee_phone_response = requests.post(detail_consignee_phone, headers=zhu_headers,
                                                            data=form_data)
            detail_consignee_phone_json = detail_consignee_phone_response.json()["userdata"]["virtualNumberInfo"]
            jingdong_phone = detail_consignee_phone_json["virtualNumber"]
            order_create_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data["orderCreateDate"] / 1000))

            add_jingdong_order = {
                "branch_id": "广州金穗隆信息科技股份有限公司",
                "jingdong_business_model": "电商销售",
                "jingdong_order_id": jingdong_order_id,
                "jingdong_order_status": jingdong_order_status,
                "jingdong_consignee_name": jingdong_consignee_name,
                "jingdong_consignee_address": jingdong_consignee_address,
                "jingdong_phone": jingdong_phone,
                "order_create_date": order_create_date
            }
            add_jingdong_order_body = []
            for detail_data in data["orderDetailList"]:
                jd_price = detail_data['jdPrice']
                procurement_single_price = detail_data["poPrice"]
                ware_num = detail_data["wareNum"]
                jd_total_price = jd_price * ware_num
                procurement_total_price = procurement_single_price * ware_num
                ware_name = detail_data["wareName"]
                sku = detail_data["sku"]
                add_jingdong_order_dict = {
                    # "jingdong_ware_name": ware_name,
                    "jingdong_sku": sku,
                    "jingdong_ware_brand": "",
                    "jingdong_ware_category": "",
                    "jingdong_ware_model": "",
                    "jingdong_ware_num": ware_num,
                    "jingdong_jd_price": jd_price,
                    "jingdong_jd_total_price": jd_total_price,
                    "jingdong_procurement_single_price": procurement_single_price,
                    "jingdong_procurement_total_price": procurement_total_price,
                }
                add_jingdong_order_body.append(add_jingdong_order_dict)
            requests_dict = {
                "add_jingdong_order": add_jingdong_order,
                "add_jingdong_order_bodys": {
                    "add_jingdong_order_body": add_jingdong_order_body
                }
            }
            zhu_jingdong_orders_messages.append(requests_dict)
        print(f"jingdong_orders_messages:{zhu_jingdong_orders_messages}")
        return zhu_jingdong_orders_messages

    def jingdong_orders_process(self,analysis_date):
        daily_start_time = f"{analysis_date.date()}"
        end_time = f"{analysis_date.date()}"
        # monthly_start_time = f"{analysis_date.replace(day=1).date()} 00:00:00"
        print(daily_start_time,end_time)
        daily_zi_jingdong_orders_messages = self.get_daily_zi_orders(daily_start_time, end_time)
        time.sleep(2)
        daily_zhu_jingdong_orders_messages = self.get_daily_zhu_orders(daily_start_time, end_time)

        for i in daily_zi_jingdong_orders_messages:
            daily_zi_jingdong_orders_json_data = json.dumps({"request": i}, ensure_ascii=False)
            daily_zi_jingdong_orders_dict_data = json.loads(daily_zi_jingdong_orders_json_data)
            SaveJingdongSynchronizationDatas(daily_zi_jingdong_orders_dict_data).save_orders()
        for i in daily_zhu_jingdong_orders_messages:
            daily_zhu_jingdong_orders_json_data = json.dumps({"request": i}, ensure_ascii=False)
            daily_zhu_jingdong_orders_dict_data = json.loads(daily_zhu_jingdong_orders_json_data)
            SaveJingdongSynchronizationDatas(daily_zhu_jingdong_orders_dict_data).save_orders()


class DetailAnalyze():
    def __init__(self,analysis_date):
        self.analysis_date = analysis_date


    def load_data(self,csv_file):
        """CSV数据加载和预处理（文件不存在时返回空DataFrame）"""

        def safe_read_csv(path, date_columns):
            """安全读取CSV文件（文件不存在返回空DataFrame）"""
            try:
                return pd.read_csv(path, parse_dates=date_columns)
            except FileNotFoundError:
                return pd.DataFrame()

        def load_and_process(csv_file):
            """通用加载和处理逻辑"""
            # 加载原始数据（文件不存在时返回空DataFrame）
            df = safe_read_csv(csv_file, ['order_create_date'])

            if df.empty:  # 如果主文件不存在，直接返回空DataFrame
                return pd.DataFrame()

            df_deep = df.copy()

            # 过滤需删除的订单
            return df_deep[df_deep['jingdong_order_status']!="删除"]


        # 加载并处理子数据和主数据
        df = load_and_process(csv_file)
        # print(combined_df)
        return df

    def daily_analysis(self,csv_file):
        for i in reversed(range(1,4)):
            analysis_date = datetime.now() - timedelta(days=i)
            GetOrderDatas().jingdong_orders_process(analysis_date)

        """
        Perform daily analysis for the specified date
        """
        df = self.load_data(csv_file)
        df['order_create_date'] = pd.to_datetime(df['order_create_date'], errors='coerce')
        # Filter data for the specific date
        daily_df = df[df['order_create_date'].dt.date == self.analysis_date.date()]

        # 1. Total daily orders
        total_orders = daily_df['jingdong_order_id'].nunique()
        total_products = daily_df['jingdong_ware_num'].sum()
        jingdong_jd_total_price = daily_df['jingdong_jd_total_price'].sum()
        total_order_amount = daily_df['jingdong_procurement_total_price'].sum() / 1.13

        # 4. Monthly analysis for the same month
        monthly_df = df[
            (df['order_create_date'].dt.year == self.analysis_date.year) &
            (df['order_create_date'].dt.month == self.analysis_date.month)&
            (df['order_create_date'].dt.day <= self.analysis_date.day)
            ]
        # print(monthly_df)
        monthly_total_orders = monthly_df['jingdong_order_id'].nunique()
        monthly_total_products = monthly_df['jingdong_ware_num'].sum()
        monthly_jingdong_jd_total_price = monthly_df['jingdong_jd_total_price'].sum()
        monthly_total_order_amount = monthly_df['jingdong_procurement_total_price'].sum() / 1.13
        result = {
            'daily_totals': {
                'total_orders': total_orders,
                'total_products': total_products,
                'jingdong_jd_total_price': jingdong_jd_total_price,
                'total_order_amount': total_order_amount
            },
            'monthly_totals': {
                'total_orders': monthly_total_orders,
                'total_products': monthly_total_products,
                'jingdong_jd_total_price': monthly_jingdong_jd_total_price,
                'total_order_amount': monthly_total_order_amount
            }
        }
        print(result)
        return result

# if __name__ == '__main__':
#     analysis_date = datetime.now() - timedelta(days=1)
#     GetOrderDatas().jingdong_orders_process(analysis_date)
#
#     # 将字符串转换为日期对象
#     date_obj = datetime.strptime(analysis_date.strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S')
#
#     # 获取当前日期的年份和月份
#     current_year = date_obj.year
#     current_month = date_obj.month
#     # directory = f'all_jingdong_order_datas/京东订单-{current_year}'
#     csv_file = f'all_jingdong_order_datas/京东订单-{current_year}/京东订单-{current_year}-{current_month}.csv'
#
#     DetailAnalyze(analysis_date).daily_analysis(csv_file)


